package com.example.costumview.customview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

public class MyViewPager extends ViewGroup {

    private float mLastX;

    public MyViewPager(Context context) {
        super(context);
    }

    public MyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            child.measure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            child.layout(i * getMeasuredWidth(), t, (i + 1) * getMeasuredWidth(), b);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastX=x;
                break;
            case MotionEvent.ACTION_MOVE:
                float dx = mLastX - x;
                float oldScrollX = getScaleX();
                float preScrollX = oldScrollX + dx;
                if (preScrollX>(getChildCount()-1)*getWidth()){
                    preScrollX=(getChildCount()-1)*getWidth();
                }
                if (preScrollX<0){
                    preScrollX=0;
                }
                scrollTo((int) preScrollX,getScrollY());
                mLastX=x;
                break;
        }
        return true;
    }
}
